package com.gangan.controller.web;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gangan.controller.common.BaseController;
import com.gangan.model.Disease;
import com.gangan.model.User;
import com.gangan.model.view.DiseaseTreeView;
import com.gangan.service.IDiseaseService;
import com.gangan.tools.MessageBean;
import com.gangan.tools.TreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-09-04
 */
@Api(description = "*疾病模块控制层")
@RestController
@RequestMapping("/disease")
public class DiseaseController extends BaseController {

    @Autowired
    IDiseaseService diseaseService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ApiOperation(value="疾病列表", notes="根据相关条件查询列表数据")
    public MessageBean list(Page page){
        return resultSuccess(diseaseService.page(page));
    }
    @RequestMapping(value = "/diseaseTree",method = RequestMethod.GET)
    @ApiOperation(value="疾病树状数据", notes="获取疾病树状图数据")
    public MessageBean diseaseTree(){
        return resultSuccess(TreeUtil.buildByLoop(diseaseService.list().stream()
                 .map(DiseaseTreeView::new)
                .collect(Collectors.toList()),0));
    }

    @RequestMapping(value = "/del",method = RequestMethod.POST)
    @ApiOperation(value="移除疾病", notes="根据自增主键移除数据")
    public MessageBean del(Integer id){
        if(CollectionUtils.isNotEmpty(diseaseService.list(Wrappers.<Disease>query().lambda().eq(Disease::getParentId , id)))){
            return resultFailed("该疾病下有子疾病，不可删除");
        }
        return resultSuccess(diseaseService.removeById(id));
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiOperation(value="新增疾病", notes="将提交的数据保存到数据库")
    public MessageBean add(Disease add){
        return resultSuccess(diseaseService.save(add));
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiOperation(value="编辑疾病", notes="根据主键修改数据")
    public MessageBean edit(Disease edit){
        return resultSuccess(diseaseService.updateById(edit));
    }


}
